package cn.zhentao.mapper;

import cn.zhentao.pojo.TutorSession;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI搜题会话Mapper
 * 
 * @author zhentao
 */
@Mapper
public interface TutorSessionMapper extends BaseMapper<TutorSession> {
    
    /**
     * 根据用户ID和会话名称查找会话
     */
    @Select("SELECT * FROM tutor_sessions WHERE user_id = #{userId} AND session_name = #{sessionName} " +
            "AND status = 'ACTIVE' ORDER BY created_time DESC LIMIT 1")
    TutorSession findByUserIdAndSessionName(@Param("userId") Long userId, 
                                          @Param("sessionName") String sessionName);
    
    /**
     * 根据用户ID获取活跃会话列表
     */
    @Select("SELECT * FROM tutor_sessions WHERE user_id = #{userId} AND status = 'ACTIVE' " +
            "ORDER BY last_message_time DESC")
    List<TutorSession> getActiveSessionsByUserId(@Param("userId") Long userId);
    
    /**
     * 根据题目ID查找会话
     */
    @Select("SELECT * FROM tutor_sessions WHERE original_question_id = #{questionId} " +
            "AND status = 'ACTIVE' ORDER BY created_time DESC LIMIT 1")
    TutorSession getSessionByQuestionId(@Param("questionId") Long questionId);
    
    /**
     * 更新最后消息时间
     */
    @Update("UPDATE tutor_sessions SET last_message_time = #{lastMessageTime}, " +
            "updated_time = NOW() WHERE id = #{sessionId}")
    int updateLastMessageTime(@Param("sessionId") Long sessionId, 
                             @Param("lastMessageTime") LocalDateTime lastMessageTime);
    
    /**
     * 关闭会话
     */
    @Update("UPDATE tutor_sessions SET status = 'CLOSED', updated_time = NOW() WHERE id = #{sessionId}")
    int closeSession(@Param("sessionId") Long sessionId);
}
